import { BaseComponent } from './components/baseComponent';
import { ShellIntegrationService } from './services/shellIntegration';
import { AppComponents } from './components/app-components/app-components';
import { CommonComponents } from './components/common-components/common-components';
import { LDCManager } from './common/LDCManage/LDCManager';
import { businsessHttpServer } from './common/http/http-server';
import { MessageBoxService } from './components/messageBox/messageBoxService';
import { LocalstorageDataManage } from './common/localstoreage/localstoreageDataManage';
import { TimeManager } from './common/timeManager';
import { InitializationService } from './pages/initialization/index';
import { PrividerService } from './pages/initialization/prividerService';
import { Subscription, Observable } from 'rxjs';
import { SeedDataManage } from './../assets/mock-data/seed';
import { expeditionOrdersService } from './services/expeditionOrders';
import { HomePageService } from './pages/home/index';
import { Input, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef } from "@angular/core";
import { ConfirmMessageResult } from './components/messageBox/confirmMessage';
import { currentProject } from './../currentConfig';

import {
	Component,
	OnInit,
	ViewEncapsulation
} from '@angular/core';
import { Router } from "@angular/router";
import { NavigateManage } from "./common/navigateManage";

@Component({
	selector: 'base-app',
	encapsulation: ViewEncapsulation.None,
	styleUrls: [
		'./app.component.scss'
	],
	template: `
    <common-components></common-components>
    <app-components></app-components>
    <md-sidenav-container class="app-container">
		<md-sidenav #sidenav class="sidenav">
			<ul>
				<li *ngFor="let sidenavOption of sidenavOptions" routerLink={{sidenavOption.routerLink}} (click)="sidenav.toggle()"><span class="nav-item">
					<i class={{sidenavOption.class}}></i>
					<span class="title">{{sidenavOption.title}}</span></span>
				</li>
				<li *ngIf="currentProject == 'chef'" (click)="sidenav.toggle() && reload()"><span class="nav-item">
					<i class="iconfont icon-reset"></i>
					<span class="title">重新加载</span></span>
				</li>
				<li (click)="sidenav.toggle() && fullScreen()"><span class="nav-item">
					<i class="iconfont icon-full-screen"></i>
					<span class="title">全屏</span></span>
				</li>
				<li class="exit" (click)="sidenav.toggle() && shutDown()">
					<span class="nav-item">
					<i class="iconfont icon-power-settings-new"></i>
					<span class="title">关机退出</span>
					</span>
				</li>
			</ul>
		</md-sidenav>

		<div class="sidenav-content">
				<main>
					<router-outlet></router-outlet>
				</main>
				<nav fxLayout="row" fxLayoutAlign="space-between">
					<button class="power" (click)="sidenav.toggle()" fxLayoutAlign="center center">
						<i class="material-icons">menu</i>
					</button>
					<ng-content></ng-content>
				</nav>
		</div>
    </md-sidenav-container>
  `
})

export class BaseAppComponent implements OnInit {
	@Input() sidenavOptions: Array<SidenavOption>
	@ViewChild(AppComponents)
	private appComponents: AppComponents;
	private currentProject;
	currentAt$;
	constructor(
		private router: Router,
		private changeDetectorRef: ChangeDetectorRef,
		private element: ElementRef
	) {

	}

	public ngOnInit() {
		this.currentProject = currentProject;
		NavigateManage.current.registerRouter(this.router);
		if (!localStorage.getItem("Terminal")) {
			const navigate = (url) => this.router.navigate([url])
			//初始化页面
			PrividerService.current.registerRouter({ navigate });
			PrividerService.current.registerMessageBoxService(MessageBoxService.current);
			this.router.navigate(['initialization/welcome']);
			// PrividerService.current.navigate(InitializationService.current.getPathByComponentName("welcome"));

			InitializationService.current.onComplete = ({ store, LDCConfig, user, token }) => {
				if(localStorage.getItem("debug")){
					LDCConfig = {
						"host": "172.16.255.45",
						"device": {
							"ppi": 96,
							"hardware": "Gigabyte Technology Co., Ltd. To be filled by O.E.M.",
							"deviceType": "desktop",
							"deviceId": "40:8D:5C:82:E3:5C",
							"platform": "Windows",
							"platformVersion": "6.1.7601",
							"os": "Microsoft Windows 7 旗舰版  Service Pack 1 64-bit",
							"appShell": "menpuji WindowsAPP 2.13.0 building 20170228",
							"appVersion": "2.13.0",
							"ldcVersion": "",
							"ip": "172.16.255.132"
						},
						"terminal": {
							"id": "576c7bac98144542ab74cd6b328bef50",
							"name": "PR1"
						},
						"version": 2,
						"state": "on",
						"services": {
							"fbs": "on",
							"fns": "on"
						}
					}
				}else{
					LDCConfig.host
				} 
				LocalstorageDataManage.current.setStore(store);
				LocalstorageDataManage.current.setLDCConfig(LDCConfig);
				LocalstorageDataManage.current.setUser(user);
				LocalstorageDataManage.current.setToken(token);
				businsessHttpServer["changePrefix"]("http://" + LDCConfig.host + ":8887");
				this.onInitializationServiceComplete && this.onInitializationServiceComplete();
			}
		} else {
			const ldcManager = new LDCManager({ storeId: LocalstorageDataManage.current.getStore().id, LDCConfigValue: LocalstorageDataManage.current.getLDCConfig() })
			ldcManager.onToggleLDCOnline = status => {
				this.appComponents.toggleLDCWarning(status);
				console.log("xxx", status);
			}
			ldcManager.start();
			NavigateManage.current.navigate(`${currentProject}Home`);
		}
		this.currentAt$ = Observable.interval(10000).map(() => TimeManager.current.getServerTime()).map((time) => {
			return this.getTime(time)
		})
	}


	onInitializationServiceComplete: () => void

	getTime(time) {
		const serverTime = this.formatTime(time);
		return serverTime;
	}

	private formatTime(time) {
		const dateTime = new Date(time);
		const hour = dateTime.getHours();
		const minutes = dateTime.getMinutes();
		const _time = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"]
		return (_time[hour] || hour) + " : " + (_time[minutes] || minutes);
	}

	async shutDown() {
		const result = await MessageBoxService.current.Show('关机退出', '确认关机退出？');
		if (result == ConfirmMessageResult.Ok) {
			(<any>window).device.exitApp();
		}
	}

	fullScreen() {
		(<any>window).device.fullScreen(!(<any>window).device.isFullScreen());
	}

	reload(){
		location.reload();
	}

}



export interface SidenavOption {
	routerLink: string;
	// clickEventHandler:
	class: string;
	title: string;
}
